const qId = (x) => { return document.getElementById(x) }
const word = qId("word");
const text = qId("text")
const scoreEl = qId("score")
const timeEl = qId("time")
const endgameEl = qId("end-game-container")
const settingBtn = qId("settings-btn")
const settings = qId("settings")
const settingsForm = qId("settings-form")
const difficultySelect = qId("difficulty");

const words = [
    "apple",
    "joke",
    "face"
]
let randomWord;
let difficulty=localStorage.getItem("difficulty")?localStorage.getItem("difficulty"):'medium';
let score = 0

let time = 10
difficultySelect.value=difficulty
function getRandomWord() {
    return words[Math.floor(Math.random() * words.length)];
}
function addWordToDom() {
    randomWord = getRandomWord()
    word.innerHTML = randomWord;
}
function updateScore() {
    score++;
    scoreEl.innerHTML = score
}
function gameOver() {
    endgameEl.innerHTML = `
        <h1>时间结束了</h1>
        <p>你的最终分数吃${score}</p>
        <button onclick="location.reload()">再来一次</button>
    `
    endgameEl.style.display='flex'
}
function updateTime(){
    time--
    timeEl.innerHTML=`${time}s`
    if(time === 0){
        clearInterval(gameLoop);
        gameOver()
    }
}
text.addEventListener("input",  (e)=> {
    const insertedText = e.target.value;

    if (insertedText === randomWord) {
        addWordToDom()
        updateScore()
        
        e.target.value = ''
        switch(difficulty){
            case "hard": time+=2;break;
            case "medium": time+=3;break;
            case "easy": time+=5;break;
        }
        updateTime()
    }
})
text.focus()
let gameLoop = setInterval(() => {
    time--;
    timeEl.innerHTML = `${time}s`
    if (time === 0) {
        clearInterval(gameLoop)
        gameOver()
    }
}, 1000);

settingBtn.addEventListener("click",()=>{
    settings.classList.toggle('hide')
})
settingsForm.addEventListener("change",(e)=>{
    difficulty=e.target.value
    localStorage.setItem('difficulty',difficulty)
})
addWordToDom()